import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * Created by PZhang on 2015/8/27.
 */
public class InputThread implements Runnable {
    Socket socket;
    BufferedReader bufferedReader = null;
    boolean flag = true;

    public InputThread(Socket socket) {
        this.socket = socket;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        while (flag) {
            if (!socket.isClosed()) {
                try {
                    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    String inmsg = bufferedReader.readLine();
                    if (inmsg.equals(null) || inmsg.equals("quit")) {
                        flag = false;
                    } else {
                        System.out.println(inmsg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        try {
            bufferedReader.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
